//
//  ZFBaseViewController.swift
//  WeiBoAPP
//
//  Created by 张学飞 on 2018/12/28.
//  Copyright © 2018 zxf. All rights reserved.
//

import UIKit
import SVProgressHUD

// 设置block
typealias kLoginSuccessBlock = ()->Void  // 声明闭包


/**
 swift 中利用extension 可以吧‘函数’按照功能分类管理，便于阅读和维护，
 注意：
 1、extension 中不能有属性
 2、extension 中不能重写父类方法！重写父类方法是子类的职责，扩展是对类的扩展
 */

class ZFBaseViewController: UIViewController {

    var tableView:UITableView?
    var visitorView:ZFVisitorView?
    
    var isPullup = false
    var isLogin = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        setupUI()
        loadData()
        //登录成功通知
        setupNotification()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    //MARK: - Action methods
    
    //加载数据
    func loadData() {
        
    }

    //刷新
    @objc func  refreshData(){
    
        refreshController?.endRefreshing()
    }
    
    
    //MARK: - Set methods
    override var title: String?
    {
        didSet {
            navItem.title = title
        }
    }
    

    
    //MARK: - 懒加载
    lazy var navgationBgVIew = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: kNavigationHeight))
    //自定义导航条
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: kStatusBarHeight, width: UIScreen.main.bounds.width, height:kNavigationBarHeight))
    
    lazy var navItem:UINavigationItem = UINavigationItem()
    var refreshController: UIRefreshControl? //刷新空间
    
}

extension ZFBaseViewController
{
    //设置UI
    @objc func setupUI()  {
        automaticallyAdjustsScrollViewInsets = false
        setupNavUI()
        isLogin ? setupTableView() :setupVisitorView()
        
    }
    
    // MARK: 设置导航条
    @objc  func setupNavUI()
    {
        view.backgroundColor = UIColor.white //UIColor.random()
        
        navgationBgVIew.backgroundColor = UIColor.init(generalHexStr: "#f6f6f6")
        view.addSubview(navgationBgVIew)
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
        //设置nav的渲染颜色

        navigationBar.barTintColor = UIColor.init(generalHexStr: "#f6f6f6")
        navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.darkGray]
    }
    
    
    @objc func setupTableView() {
        
        if tableView != nil {
            return
        }
        
        var frame = view.bounds;
        frame.origin.y = kNavigationHeight
        frame.size.height = UIScreen.main.bounds.size.height - kNavigationHeight
        tableView = UITableView(frame:frame, style: .plain)
        
        view.addSubview(tableView!)
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        //设置数据源方法
        tableView?.dataSource = self
        tableView?.delegate = self
//        tableView?.contentInset = UIEdgeInsets(top:0,
//                                               left: 0,
//                                               bottom:tabBarController?.tabBar.bounds.height ?? 49,
//                                               right: 0)
        //修改指示器的缩进,强行解包为了拿到一个必有的 inset
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        tableView?.separatorStyle = .none
        //刷新控件
        refreshController = UIRefreshControl()
        tableView?.addSubview(refreshController!)
        refreshController?.addTarget(self, action:#selector(refreshData), for: .valueChanged)
        
    }

    func setupVisitorView()  {
        
        if visitorView != nil {
            if isLogin == false {
                view.insertSubview(visitorView!, belowSubview: navigationBar)
            }else{
                visitorView?.removeFromSuperview()
            }
            
            return
        }
         visitorView = ZFVisitorView(frame: view.bounds)
//        view.addSubview(visitorView)
        view.insertSubview(visitorView!, belowSubview: navigationBar)
    }
    
    
}

// MARK: -  extensionZFBaseViewController
extension ZFBaseViewController:UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //判断是不是最后一行
        let row = indexPath.row
        let  section = tableView.numberOfSections - 1
        if  row < 0 || section < 0 {
            return
        }
  
        let cout = tableView.numberOfRows(inSection: section)
        
        if row == (cout - 1) && !isPullup {
            isPullup = true
            print("最后一行，且没有下a拉刷新动作")
            refreshData()
        }
        
    }
}

// MARK: - 登录成功通知
extension ZFBaseViewController {
    
    func setupNotification ()  {
        NotificationCenter.default.addObserver(self, selector: #selector(userLoginSuccessActon), name: NSNotification.Name?(NSNotification.Name(rawValue: WB_LoginRegistSuccess_Notification)), object: nil)
    }
    
    @objc func userLoginSuccessActon() {
        
        isLogin = true
        
        setupUI()

        print("登录成功")
    }
    
    
    // 弹框
    func showAlert(titleStr:String?,message:String?) -> () {
    
        // 弹框内容
        var newTitleStr = titleStr
        if (newTitleStr == nil) {
            newTitleStr = "温馨提示"
        }
        
        let alertController = UIAlertController.init(title: titleStr, message: message, preferredStyle: UIAlertController.Style.alert)
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { _ in
            
        }
        
        let okAction = UIAlertAction(title: "确定", style: UIAlertAction.Style.default) { _ in
            
        }
        
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)

        self.present(alertController, animated: true, completion: nil)
    }
    
    // 提示
    func showHuDing(title:String?,msg:String?) -> () {
        
        ///这种纯文字的显示时候文字会偏下，效果没有那么完美，可以用MBProgressHUDdle或Toast或找个swift的库
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.none)
//        SVProgressHUD.setInfoImage(UIImage(named: "") ?? UIImage())
        SVProgressHUD.setImageViewSize(CGSize.zero)
        SVProgressHUD.setMinimumSize(CGSize(width: 10, height: 10))
        SVProgressHUD.setFont(UIFont.systemFont(ofSize: 16))
        SVProgressHUD.showInfo(withStatus: msg)
        SVProgressHUD.dismiss(withDelay: 1.5)
        
    }
    // 登录中
    func showHuWaiting(title:String?,msg:String?) -> () {
        
        ///这种纯文字的显示时候文字会偏下，效果没有那么完美，可以用MBProgressHUDdle或Toast或找个swift的库
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
        SVProgressHUD.show(withStatus: msg)
        
    }
    // 关闭弹框
    func dismissHuD() {
        
        ///这种纯文字的显示时候文字会偏下，效果没有那么完美，可以用MBProgressHUDdle或Toast或找个swift的库
        SVProgressHUD.dismiss(withDelay: 1.5)
    }
    
    
    // 登录成功数据
    func loginSuccessInfo(info:Any) {
        
        UserDataConfig.shared.isLogin = true
    }
    // 退出登录
    func loginOut() {
        
        UserDataConfig.shared.clearUserInfo()
        UserDataConfig.shared.isLogin = false
        
    }
    
    
}
